import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, classification_report
from sklearn.model_selection import GridSearchCV

# 读取数据集
data = pd.read_excel(r"C:\pythondata\bigdata.xlsx")

# 数据预处理
X = data.drop('species', axis=1)  # 特征矩阵
y = data['species']  # 目标变量

# 划分数据集
X_train_val, X_test, y_train_val, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_train, X_val, y_train, y_val = train_test_split(X_train_val, y_train_val, test_size=0.25, random_state=42)

# 决策树模型
dt_model = DecisionTreeClassifier()
dt_params = {'criterion': ['gini', 'entropy'], 'max_depth': [3, 5, 7]}
dt_grid = GridSearchCV(dt_model, dt_params)
dt_grid.fit(X_train, y_train)
dt_best_params = dt_grid.best_params_
dt_best_model = dt_grid.best_estimator_

# 贝叶斯模型
nb_model = GaussianNB()
nb_model.fit(X_train, y_train)

# SVM模型
svm_model = SVC()
svm_params = {'C': [0.1, 1, 10], 'kernel': ['linear', 'rbf']}
svm_grid = GridSearchCV(svm_model, svm_params)
svm_grid.fit(X_train, y_train)
svm_best_params = svm_grid.best_params_
svm_best_model = svm_grid.best_estimator_

# 决策树模型评估
dt_val_pred = dt_best_model.predict(X_val)
dt_val_accuracy = accuracy_score(y_val, dt_val_pred)
dt_val_report = classification_report(y_val, dt_val_pred)

# 贝叶斯模型评估
nb_val_pred = nb_model.predict(X_val)
nb_val_accuracy = accuracy_score(y_val, nb_val_pred)
nb_val_report = classification_report(y_val, nb_val_pred)

# SVM模型评估
svm_val_pred = svm_best_model.predict(X_val)
svm_val_accuracy = accuracy_score(y_val, svm_val_pred)
svm_val_report = classification_report(y_val, svm_val_pred)

print('决策树模型最佳参数:', dt_best_params)
print('决策树模型验证集准确率:', dt_val_accuracy)
print('决策树模型分类报告:\n', dt_val_report)

print('贝叶斯模型验证集准确率:', nb_val_accuracy)
print('贝叶斯模型分类报告:\n', nb_val_report)

print('SVM模型最佳参数:', svm_best_params)
print('SVM模型验证集准确率:', svm_val_accuracy)
print('SVM模型分类报告:\n', svm_val_report)

val_accuracies = [dt_val_accuracy, nb_val_accuracy, svm_val_accuracy]
best_model_index = val_accuracies.index(max(val_accuracies))
best_model = ['决策树', '贝叶斯', 'SVM'][best_model_index]

print('最佳模型:', best_model)
